<?php
class WikiBlock extends BlockInstance {
	public $CI;
	
	function WikiBlock()
	{
		$this->CI =& get_instance();
	}
	
	function __call($m, $a)
	{
		global $BBX;
		
		$this->CI->load->helper('typography');
		$this->CI->load->helper('text');
		$this->CI->load->helper('url');
		
		if (preg_match('/[a-z]+_([a-z]+)/', $m, $matches))
		{
			/**
			 * Set things up
			 */
			if ($matches[1] == 'content')
			{
				$inst	  = $a[0]['data'];
				$content  = $a[1];
			}
			elseif ($matches[1] == 'homepage')
			{
				$inst	  = $a[0]['data'];
				$content  = new stdClass;
				$content->id = (int)(-1 * ($BBX['bricabox']->id . $inst->id));
				
				$data['content'] = $content;
			}
			
			/**
			 * Load things
			 */
			$versions = $this->load_versions($content->id);
			$is_empty = false;
			
			if ($versions)
				$first_ver = $versions->first_row();
			else
			{
				$first_ver 		  = new stdClass();
				$first_ver->value = !strlen($BBX['bricabox']->default_wiki_text)
					? 'No one has added anything to this wiki yet.'
					: $BBX['bricabox']->default_wiki_text;
				$first_ver->id	  = -1;
				$is_empty 		  = true;
			}
			
			$data['bricabox']  = $BBX['bricabox'];
			$data['inst']  	   = $inst;
			$data['first_ver'] = $first_ver;
			$data['versions']  = $versions;
			$data['value']	   = $is_empty ? $BBX['bricabox']->default_wiki_text : $first_ver->value;
			$this->CI->load->view('blocks/wiki/content', $data);
		}
	}
	
	function load_versions($instance_id)
	{
		// NOTE: instance_id is really content_id (legacy reason)
		$query = $this->CI->db->query('select * from wiki_versions where instance_id = ? order by created_at desc', array($instance_id));
		if (!$query->num_rows())
			return false;
		else
			return $query;
	}
}
?>